package com.googlecode.antilopebpm.variable.matcher.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.DiscriminatorType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HibernateDiscriminatorMatchHelper {
	private static final Logger logger = LoggerFactory
			.getLogger(HibernateDiscriminatorMatchHelper.class);
	protected SessionFactory sessionFactory;

	public boolean matches(Object value, Class discriminatorTypeClass) {
		boolean matches = false;

		Class valueClass = value.getClass();
		if (value instanceof HibernateProxy) {
			valueClass = valueClass.getSuperclass();
		}

		if (sessionFactory != null) {
			ClassMetadata classMetadata = sessionFactory
					.getClassMetadata(valueClass);
			matches = ((classMetadata != null) && (classMetadata
					.getIdentifierType().getClass() == discriminatorTypeClass));
		} else {
			logger
					.debug("no current sessionFactory so valueClass cannot be stored as a string-id-ref to a hibernate object");
			matches = false;
		}
		return matches;
	}
}
